/*circle-progress 画圆 start*/
(function($) {
    function CircleProgress(config) {
        this.init(config);
    }
	//第一步
    CircleProgress.prototype = {
        value: 0.0,
        size: 150.0,
        thickness: 'auto',
        fill: {
            gradient: ['#3aeabb', '#fdd250']
        },
        emptyFill: 'rgba(0, 0, 0, .05)',
        animation: {
            duration: 1200,
            easing: 'circleProgressEasing'
        },
        animationStartValue: 0.0,
        reverse: false,
        lineCap: 'butt',
        constructor: CircleProgress,
        el: null,
        canvas: null,
        ctx: null,
        radius: 0.0,
        arcFill: null,
        lastFrameValue: 0.0,
        init: function(config) {
            $.extend(this, config);
            this.radius = this.size / 2;
            this.initWidget();
            this.initFill();
            this.draw();
        },
        initWidget: function() {
            var canvas = this.canvas = this.canvas || $('<canvas>').prependTo(this.el)[0];
            canvas.width = this.size;
            canvas.height = this.size;
            this.ctx = canvas.getContext('2d');
        },
        initFill: function() {
            var self = this,
                fill = this.fill,
                ctx = this.ctx,
                size = this.size;

            if (!fill)
                throw Error("The fill is not specified!");

            if (fill.color)
                this.arcFill = fill.color;

            if (fill.gradient) {
                var gr = fill.gradient;

                if (gr.length == 1) {
                    this.arcFill = gr[0];
                } else if (gr.length > 1) {
                    var ga = fill.gradientAngle || 0, // gradient direction angle; 0 by default
                        gd = fill.gradientDirection || [
                            size / 2 * (1 - Math.cos(ga)), // x0
                            size / 2 * (1 + Math.sin(ga)), // y0
                            size / 2 * (1 + Math.cos(ga)), // x1
                            size / 2 * (1 - Math.sin(ga))  // y1
                        ];

                    var lg = ctx.createLinearGradient.apply(ctx, gd);

                    for (var i = 0; i < gr.length; i++) {
                        var color = gr[i],
                            pos = i / (gr.length - 1);

                        if ($.isArray(color)) {
                            pos = color[1];
                            color = color[0];
                        }

                        lg.addColorStop(pos, color);
                    }

                    this.arcFill = lg;
                }
            }


            function setImageFill() {
                var bg = $('<canvas>')[0];
                bg.width = self.size;
                bg.height = self.size;
                bg.getContext('2d').drawImage(img, 0, 0, size, size);
                self.arcFill = self.ctx.createPattern(bg, 'no-repeat');
                self.drawFrame(self.lastFrameValue);
            }
        },

        draw: function() {
            if (this.animation)
                this.drawAnimated(this.value);
            else
                this.drawFrame(this.value);
        },
        drawFrame: function(v) {
            this.lastFrameValue = v;
            this.ctx.clearRect(0, 0, this.size, this.size);
            this.drawEmptyArc(v);
            this.drawArc(v);
        },
        drawArc: function(v) {
            var ctx = this.ctx,
                r = this.radius,
                t = this.getThickness(),
                a = this.startAngle;

            ctx.save();
            ctx.beginPath();

            if (!this.reverse) {
                ctx.arc(r, r, r - t / 2, a, a + Math.PI * 2 * v);
            } else {
                ctx.arc(r, r, r - t / 2, a - Math.PI * 2 * v, a);
            }

            ctx.lineWidth = t;
            ctx.lineCap = this.lineCap;
            ctx.strokeStyle = this.arcFill;
            ctx.stroke();
            ctx.restore();
        },
        drawEmptyArc: function(v) {
            var ctx = this.ctx,
                r = this.radius,
                t = this.getThickness(),
                a = this.startAngle;

            if (v < 1) {
                ctx.save();
                ctx.beginPath();

                if (v <= 0) {
                    ctx.arc(r, r, r - t / 2, 0, Math.PI * 2);
                } else {
                    if (!this.reverse) {
                        ctx.arc(r, r, r - t / 2, a + Math.PI * v, a);
                    } else {
                        ctx.arc(r, r, r - t / 2, a, a - Math.PI * v);
                    }
                }

                ctx.lineWidth = t;
                ctx.strokeStyle = this.emptyFill;
                ctx.stroke();
                ctx.restore();
            }
        },
        drawAnimated: function(v) {
            var self = this,
                el = this.el;

            el.trigger('circle-animation-start');

            $(this.canvas)
                .stop(true, true)
                .css({ animationProgress: 0 })
                .animate({ animationProgress: 1 }, $.extend({}, this.animation, {
                    step: function(animationProgress) {
                        var stepValue = self.animationStartValue * (1 - animationProgress) + v * animationProgress;
                        self.drawFrame(stepValue);
                        el.trigger('circle-animation-progress', [animationProgress, stepValue]);
                    },
                    complete: function() {
                        el.trigger('circle-animation-end');
                    }
                }));
        },
        getThickness: function() {
            return $.isNumeric(this.thickness) ? this.thickness : this.size / 14;
        }
    };

	//第二步
    $.circleProgress = {
        defaults: CircleProgress.prototype
    };
    //第三步
    $.easing.circleProgressEasing = function(x, t, b, c, d) {
        if ((t /= d / 2) < 1)
            return c / 2 * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t + 2) + b;
    };
	//第四步
    $.fn.circleProgress = function(config) {
        var dataName = 'circle-progress';

        if (config == 'widget') {
            var data = this.data(dataName);
            return data && data.canvas;
        }

        return this.each(function() {
            var el = $(this),
                instance = el.data(dataName),
                cfg = $.isPlainObject(config) ? config : {};

            if (instance) {
                instance.init(cfg);
            } else {
                cfg.el = el;
                instance = new CircleProgress(cfg);
                el.data(dataName, instance);
            }
        });
    };
})(jQuery);
/*circle-progress 画圆 end 8月17日搬动 */

/*circle-progress Examples 百分比变化*/
filter_fn();
function filter_fn(){
    circle_progress();
    function circle_progress(){
        var $percent_1 =$('.Pre_carbon').val();
        var $percent_2 =$('.Re_osmosis').val();

        $('.first.circle').circleProgress({
                value: $percent_1/100,
                startAngle: -Math.PI/3,
                lineCap: 'round',
                fill: { color: '#2ebaea' }
            }).on('circle-animation-progress', function(event, progress) {
            $(this).find('strong').html(parseInt($percent_1 * progress) + '<i>%</i>');
        });

        $('.second.circle').circleProgress({
            value: $percent_1/100,
            startAngle: -Math.PI/3,
            lineCap: 'round',
            fill: { color: '#2ebaea' }
        }).on('circle-animation-progress', function(event, progress) {
            $(this).find('strong').html(parseInt($percent_1 * progress) + '<i>%</i>');
        });

        $('.third.circle').circleProgress({
            value: $percent_2/100,
            startAngle: -Math.PI/3,
            lineCap: 'round',
            fill: { color: '#ff6600' }
        }).on('circle-animation-progress', function(event, progress) {
            $(this).find('strong').html(parseInt($percent_2 * progress) + '<i>%</i>');
        });

        $('.forth.circle').circleProgress({
            value: $percent_1/100,
            startAngle: -Math.PI/3,
            lineCap: 'round',
            fill: { color: '#e80021' }
        }).on('circle-animation-progress', function(event, progress) {
            $(this).find('strong').html(parseInt($percent_1 * progress) + '<i>%</i>');
        });
    }
    /*弹出滤芯信息 start*/
    filter_infor();
    function filter_infor(){
        $('.circles_btn').children("div").click(function(){
            $('.filter_bg').css("display","block");
            $('.filter_bg').css("height",$(window).height()+"px");
            $('.life_percent').html($(this).children('.first').val()+"%");
            $('.used_num').html($(this).children(".second").val()+"L");
            if($(this).index() == 2){
                var i = 2;
            }else{
                var i = 1;
            }
            $('.reset_btn').unbind('click').click(function(){
                $('.undbing_bg').css("display","block");
                $('.undbing_bg').css("height",$(window).height()+"px");
                $('.no_btn').unbind('click').click(function(){
                    $('.undbing_bg').css("display","none");
                });
                $('.yes_btn').unbind('click').click(function(){
                    $.ajax({
                        url:"/api/device/control",
                        type:"post",
                        data:{command:"reset_filter", num:i},
                        success:function(data){
                            $('.undbing_bg').css("display","none");
                            $('.filter_bg').css("display","none");
                            if(data.status.errCode == 0){
                                hint("复位成功！");
                            }else
                            {
                                hint("复位失败，请重新复位！");
                            }
                        }
                    });
                });
                
            });
            $('.calloff_btn').click(function(){
                $('.filter_bg').css("display","none");
            });
        });
    }
    /*弹出滤芯信息 end*/
}
/*circle-progress Examples 百分比变化 end*/	
/*文本左右拖拽  start*/
function id(obj) {
	return document.getElementById(obj);
}
function bind(obj, ev, fn) { 
	if (obj.addEventListener) {
		obj.addEventListener(ev, fn, false);
	} else {
		obj.attachEvent('on' + ev, function() {
			fn.call(obj);
		});
	}
}
function addClass(obj, sClass) { 
	var aClass = obj.className.split(' ');
	if (!obj.className) {
		obj.className = sClass;
		return;
	}
	for (var i = 0; i < aClass.length; i++) {
		if (aClass[i] === sClass) return;
	}
	obj.className += ' ' + sClass;
}

function removeClass(obj, sClass) { 
	var aClass = obj.className.split(' ');
	if (!obj.className) return;
	for (var i = 0; i < aClass.length; i++) {
		if (aClass[i] === sClass) {
			aClass.splice(i, 1);
			obj.className = aClass.join(' ');
			break;
		}
	}
}
//默认事件
bind(document,"touchmove",function(ev){
	ev.preventDefault();
});
//text触屏滑动

function fnTab_txt()
{
    var oTab=id("text");
    var oList=id("textList");
    var aNav=id("textNav").children;
    var iNow=0;//任意自然数
    var iX=0;
    var iW=300;
    var oTimer=0;
	var iStartTouchX=0;
	var iStartX=0;
	bind(oTab,"touchstart",fnStart);
	bind(oTab,"touchmove",fnMove);
	bind(oTab,"touchend",fnEnd);
	//拖拽
	function fnStart(ev)
	{
		oList.style.transition="none";
		ev=ev.changedTouches[0];//触发当前手指列表第一个
		iStartTouchX=ev.pageX;//获取当前手指的目标
		iStartX=iX;
		clearInterval(oTimer);
	}
	function fnMove(ev)
	{
		ev=ev.changedTouches[0];
		var iDis=ev.pageX-iStartTouchX;
		iX=iStartX+iDis;
		oList.style.WebkitTransform=oList.style.transform="translateX("+iX+"px)";
	}
	function fnEnd()
	{
		iNow=iX/iW;
		iNow=-Math.round(iNow);
		if(iNow<0)//最小
		{
			iNow=0;
		}
		if(iNow>aNav.length-1)//最大
		{
			iNow=aNav.length-1;
		}
        
		tab();
	}
    function tab()
    {
        iX=-iNow*iW;
        oList.style.transition="0.2s";
        oList.style.WebkitTransform=oList.style.transform="translateX("+iX+"px)";
        for(var i=0;i<aNav.length;i++)
        {
            removeClass(aNav[i],"spanActive");
        }
        addClass(aNav[iNow],"spanActive");
    }
	
}

//footer触屏滑动

function fnTab_temp()
{
    var oTab=id("part_footer");
    var oList=id("part_scroll");
    var aNav=id("footerNav").children;
   // var aNav=id("textNav").children;
    var iNow=0;//任意自然数
    var iX=0;
    var iW=980;
    var oTimer=0;
    var iStartTouchX=0;
    var iStartX=0;
    bind(oTab,"touchstart",fnStart);
    bind(oTab,"touchmove",fnMove);
    bind(oTab,"touchend",fnEnd);
    temp_active();
    //拖拽
    function fnStart(ev)
    {
        oList.style.transition="none";
        ev=ev.changedTouches[0];//触发当前手指列表第一个
        iStartTouchX=ev.pageX;//获取当前手指的目标
        iStartX=iX;
        clearInterval(oTimer);
    }
    function fnMove(ev)
    {
        ev=ev.changedTouches[0];
        var iDis=ev.pageX-iStartTouchX;
        iX=iStartX+iDis;
        oList.style.WebkitTransform=oList.style.transform="translateX("+iX+"px)";
    }
    function fnEnd()
    {
        iNow=iX/iW;
        iNow=-Math.round(iNow);
        if(iNow<0)//最小
        {
            iNow=0;
        }
        if(iNow>aNav.length-1)//最大
        {
            iNow=aNav.length-1;
        }
        tab();
    }
    function tab()
    {
        iX=-iNow*iW;
        oList.style.transition="0s";
        oList.style.WebkitTransform=oList.style.transform="translateX("+iX+"px)";
        for(var i=0;i<aNav.length;i++)
        {
            removeClass(aNav[i],"spanActive");
        }
        addClass(aNav[iNow],"spanActive");
    }
    
}

//弹出右选项卡
$('.h_right').click(function(){
    $('.Bomb_bg').css("display","block");
    $('.Bomb_bg').css("height",$(window).height()+"px");
    $('.Bomb_bg').unbind('click').click(function(){
        $(this).css("display","none");
    })
    $('.fixing_btn').unbind('click').click(function(){
        $('.Bomb_bg').css("display","none");
    })
    $('.net_btn').unbind('click').click(function(){
        $('.Bomb_bg').css("display","none");
    })
});
//温度模块定义
function temp_active(){
            var T_set = document.getElementById("T_settings");
            var oBox = document.getElementById("slide_box");
            var block = document.getElementById("slide_b");
            var progress_width= document.getElementById("progress_width");
            var num_show = document.getElementById("T_number");
            var T_point = document.getElementById("T_point");
            var oW; 
            // 绑定touchstart事件
            num_show.innerHTML=45+"°";  
            block.addEventListener("touchstart", function(e) 
            {
               var touches = e.touches[0];
               oW = touches.clientX - block.offsetLeft;
               //阻止页面的滑动默认事件
               T_set.addEventListener("touchmove",defaultEvent,false);
            },false)
         
            block.addEventListener("touchmove", function(e) 
            {
                T_point.style.backgroundColor="#2CBAFA";
               var touches = e.touches[0];
               var oLeft = touches.clientX - oW;
               var T_overwidth = $('#slide_box').width();
               var T_num = Math.ceil(progress_width.offsetWidth/T_overwidth*100);
               var clientWidth = $(window).width();
               if(oLeft < 60) {
                oLeft = 60;
               }else if(oLeft > oBox.offsetWidth - block.offsetWidth) 
               {
                oLeft = (oBox.offsetWidth - block.offsetWidth+60);
               }
               block.style.left = oLeft + "px";
               progress_width.style.width=oLeft-60 +"px"; 
               num_show.innerHTML=T_num+"°";

               if(T_num<=45){
                    progress_width.style.backgroundColor = "#00ffff";
               }else if (T_num<=60){
                    progress_width.style.backgroundColor = "#ffcc00";
               }else{
                    progress_width.style.backgroundColor = "#d37f7f";
               }
               
            },false);
            block.addEventListener("touchend",function() 
            {
                var water_temp = $("#T_number").html();
                $.ajax({
                    url:"/api/device/control",
                    type:"post",
                    data:{command:"set_water_temperature", num:water_temp},
                    success:function(data){
                    },
                    error:function(){
                        hint('error');
                    }
                });
                T_set.removeEventListener("touchmove",defaultEvent,false);
                T_point.style.backgroundColor="#fff";

            },false);
            function defaultEvent(event) 
            {
                 event.stopPropagation();
            }
            
            $('.Bomb_bg').css("display","none");

            /*点击相应温度模式*/
            $('.sect section').unbind('click').click(function(){
                var $Array= [45,60,100];
                $temp = $Array[$(this).index()];
                var $Progress_new = $('.progress_new');
                $(this).addClass('active').siblings().removeClass('active');
                var T_overW=$('#slide_box').width();
                $Progress_new.css("width",$temp+"%");
                $('#T_number').html($temp+"°");
                if($temp <46){
                    $Progress_new.css("backgroundColor","#00ffff");
                    $('#slide_b').css("left",45+"%");
                }else if($temp <61){
                    $Progress_new.css("backgroundColor","#ffcc00");
                    $('#slide_b').css("left",59+"%");
                }else{
                    $Progress_new.css("backgroundColor","#d37f7f");
                    $('#slide_b').css("left",94+"%");
                };
                var water_temp = $("#T_number").html();
                $.ajax({
                    url:"/api/device/control",
                    type:"post",
                    data:{command:"set_water_temperature", num:water_temp},
                    success:function(data){
                    },
                    error:function(){
                        hint(data.status.errCode);
                    }
                });
            });
        }
//触屏滑动 end

//净水器所有状态
/*1 隐藏所有状态*/
function all_state(){
    $('.wash').hide();
    $('.wave_bg').hide();
    $('.ring_box').hide();
    $('.circleProgress_wrapper').hide();
    $('.circleProgress_bg').hide();
    $('.service').hide();
    $('.less_water').hide();
    $('.full_water').hide();
    $("#text").hide();
    $(".p_box").hide();
    $(".textNav").hide();
    $(".lessWater_box").hide();
    $(".service_box").hide();
    $('.shut_down').hide();
}
/*2 加水状态*/
function add_state(){
    all_state();
    $('.ring_box').show();
    $("#text").show();
    $(".p_box").show();
    $(".textNav").show();
    $('.circleProgress_wrapper').show();
    $('.circleProgress_bg').show();
    $('.wash_btn').html("冲洗");
    $(".wash_btn").css("backgroundColor","#fff");
}
/*3 冲洗状态*/
function wash_state(){
    all_state();
    $('.wash').show();
    $('.wave_bg').show();
    $("#text").show();
    $(".p_box").show();
    $(".textNav").show();
    $('.wash_btn').html("取消冲洗");
    $(".wash_btn").css("backgroundColor","#fff");
}
/*4 检修状态*/
function service(){
    all_state();
    $('.service').show();
    $(".service_box").show();
    $("#text").show();
    $(".textNav").show();
    $('.wash_btn').html("冲洗");
    $(".wash_btn").css("backgroundColor","#ccc");
}
/*5 缺水状态*/
function less_water(){
    all_state();
    $('.less_water').show();
    $(".lessWater_box").show();
    $("#text").show();
    $(".textNav").show();
    $('.wash_btn').html("冲洗");
    $(".wash_btn").css("backgroundColor","#ccc");
}
/*6 水满状态*/
function full_water(){
    all_state();
    $('.full_water').show();
    $("#text").show();
    $(".p_box").show();
    $(".textNav").show();
    $('.wash_btn').html("冲洗");
    $(".wash_btn").css("backgroundColor","#fff");
}
// 关机
function shut_down(){
    all_state();
    $('.circleProgress_bg').show();
    $('.shut_down').show();
    $('.wash_btn').html("冲洗");
    $(".wash_btn").css("backgroundColor","#ccc");
}
// 离线
function off_line(){
    all_state();
    $('.circleProgress_bg').show();
    $("#text").show();
    $(".p_box").show();
    $(".textNav").show();
    $('.hidden_txt').html('离线');
    $(".power_off").html("开机");
    $(".wash_btn").html("冲洗");
    $(".wash_btn").click(function(event){event.preventDefault()});
    $(".wash_btn").css({"backgroundColor":"#ccc","color":"#666"}); 
}